package com.tarena.lbs.attach.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarena.lbs.attach.dao.mapper.AttachMapper;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.po.AttachPO;
import com.tarena.lbs.attach.service.AttachService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.extension.toolkit.Db.updateBatchById;

@Slf4j
@Service
public class AttachServiceImpl extends ServiceImpl<AttachMapper, AttachPO> implements AttachService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchInsertBusinessInfo(List<PicUpdateParam> picParams) {
        if (picParams == null || picParams.isEmpty()) {
            log.warn("批量插入业务信息的参数列表为空");
            return true;
        }

        try {
            List<AttachPO> insertList = picParams.stream()
                    .map(this::convertToAttachPO)
                    .collect(Collectors.toList());

            // 使用MyBatis-Plus的批量插入
            boolean success = saveBatch(insertList);

            if (success) {
                // 打印插入成功的记录ID
                List<Integer> generatedIds = insertList.stream()
                        .map(AttachPO::getId)
                        .collect(Collectors.toList());
                log.info("批量插入业务信息成功，共插入 {} 条记录，生成的ID: {}",
                        insertList.size(), generatedIds);
            } else {
                log.error("批量插入业务信息失败");
            }

            return success;

        } catch (Exception e) {
            log.error("批量插入业务信息失败", e);
            throw new RuntimeException("批量插入业务信息失败", e);
        }

    }
    private AttachPO convertToAttachPO(PicUpdateParam param) {
        AttachPO attachPO = new AttachPO();

        // 不设置ID，让数据库自动生成
        // attachPO.setId(null);

        // 设置必填字段
        attachPO.setFileUuid(param.getFileUuid());
        attachPO.setBusinessType(param.getBusinessType());
        attachPO.setBusinessId(param.getBusinessId());

        // 设置默认值
        attachPO.setClientFileName(""); // 可以根据需要从参数中获取或生成
        attachPO.setContentType("image/jpeg"); // 根据实际文件类型设置
        attachPO.setStatus(0); // 默认状态

        // 设置时间戳
        long currentTime = System.currentTimeMillis();
        attachPO.setGmtCreate(currentTime);
        attachPO.setGmtModified(currentTime);

        // 设置创建人信息（根据实际业务需求设置）
        // attachPO.setCreateUserId(currentUserId);
        // attachPO.setCreateUserName(currentUserName);
        // attachPO.setModifiedUserId(currentUserId);
        // attachPO.setModifiedUserName(currentUserName);

        return attachPO;
    }
}
